package com.sudo.boot.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NioClient {
    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(new InetSocketAddress("127.0.0.1", 8888));
        // 将channel注册到Selector上，并监听连接事件
        Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            int select = selector.select();
            System.out.println("select = " + select);
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

                if (selectionKey.isConnectable()) {
                    // 正在连接
                    if (socketChannel.isConnectionPending()) {
                        socketChannel.finishConnect();
                        socketChannel.configureBlocking(false);
                        // 给服务端发消息
                        ByteBuffer send = ByteBuffer.wrap("hello server".getBytes());
                        socketChannel.write(send);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        // 设置
                    }
                } else if (selectionKey.isReadable()) {
                    // 读服务端返回的数据
                    ByteBuffer read = ByteBuffer.allocate(1024);
                    int read1 = socketChannel.read(read);
                    if (read1 != -1) {
                        System.out.println("服务端返回数据 = " + new String(read.array(), 0, read1));
                    }
                }
                iterator.remove();
            }
        }
    }
}
